<script setup lang="ts">
  import { computed, reactive, Ref, ref } from 'vue';
  import { Message, PaginationProps } from '@arco-design/web-vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import AddModal from '@/views/blog/links/components/add-modal.vue';
  import {
    columns,
    categoryOptions,
    STATUS_CONFIG,
    CATEGORY_MAP,
    StatusType,
    CategoryType,
  } from '@/views/blog/links/config';
  import {
    passLinks,
    rejectLinks,
    removeLinks,
    selectPageLinks,
  } from '@/api/links';
  import { LinksRecord } from '@/api/links/types';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();

  // 表格尺寸配置
  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const size = ref<SizeProps>('medium');

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event,
  ) => {
    size.value = val as SizeProps;
  };

  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);

  // 行选择配置
  const rowSelection = computed(() => ({
    type: 'checkbox' as const,
    checkStrictly: true,
    onlyCurrent: false,
    showCheckedAll: true,
  }));

  // 分页配置
  const pagination = reactive<PaginationProps>({
    showTotal: true,
    showPageSize: true,
    pageSizeOptions: [5, 10, 50, 100],
  });

  const categoryFieldNames = { value: 'value', label: 'label' };

  // 选中行的ID
  const selectedRowKeys: Ref<number[]> = ref([]);
  const LinksList = ref<LinksRecord[]>([]);

  const params = ref({
    pageNo: 1,
    pageSize: 10,
    name: '',
    category: '',
  });

  const getLinksList = async () => {
    setLoading(true);
    try {
      const result = await selectPageLinks(params.value);
      LinksList.value = result.data.list;
      pagination.total = result.data.total;
      pagination.current = params.value.pageNo;
      pagination.pageSize = params.value.pageSize;
    } finally {
      setLoading(false);
    }
  };

  getLinksList();

  // 查询
  const handleSearch = () => {
    params.value.pageNo = 1;
    getLinksList();
  };

  // 重置
  const handleReset = () => {
    params.value.pageNo = 1;
    params.value.name = '';
    params.value.category = '';
    getLinksList();
  };

  // 刷新
  const handleReFresh = () => {
    getLinksList();
  };

  // 切换页面
  const handlePageNoChange = (pageNo: number) => {
    params.value.pageNo = pageNo;
    getLinksList();
  };

  // 变更页数数量
  const handlePageSizeChange = (pageSize: number) => {
    params.value.pageSize = pageSize;
    getLinksList();
  };

  // 删除
  const handleDelete = async (id: number) => {
    await removeLinks([id]);
    Message.success('删除成功');
    // 重新查询
    if (LinksList.value.length === 1 && params.value.pageNo !== 1) {
      params.value.pageNo -= 1;
    }
    await getLinksList();
  };

  const addModalRef = ref();
  const handleEdit = (id: number) => {
    addModalRef.value?.handleEdit(id);
  };

  const handlePass = async () => {
    if (selectedRowKeys.value.length === 1) {
      const result = await passLinks([selectedRowKeys.value[0]]);
      Message.success(result.data);
      await getLinksList();
    } else {
      Message.error('请选中一行数据！');
    }
  };

  const handleReject = async () => {
    if (selectedRowKeys.value.length === 1) {
      const result = await rejectLinks([selectedRowKeys.value[0]]);
      Message.success(result.data);
      await getLinksList();
    } else {
      Message.error('请选中一行数据！');
    }
  };

  // 保存成功回调函数
  const handleSaveSuccess = () => {
    getLinksList();
  };
</script>

<template>
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="params"
        label-align="left"
        :label-col-props="{ span: 6 }"
        layout="inline"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="name" label="网站名称：" label-col-flex="70px">
          <a-input v-model="params.name" placeholder="请输入网站名称" />
        </a-form-item>
        <a-form-item field="category" label="分类：" label-col-flex="70px">
          <a-select
            v-model="params.category"
            :options="categoryOptions"
            :field-names="categoryFieldNames"
            placeholder="请选择分类"
            :style="{ width: '180px' }"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              v-permission="'blog:announcement:list'"
              type="primary"
              @click="handleSearch"
            >
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button type="primary" @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 10px; margin-bottom: 16px" />
  <a-row style="margin-bottom: 16px">
    <a-col :span="12">
      <a-space>
        <a-button
          v-permission="'blog:links:pass'"
          type="primary"
          :disabled="selectedRowKeys.length !== 1"
          @click="handlePass"
        >
          <template #icon>
            <icon-edit />
          </template>
          {{ $t('searchTable.operation.pass') }}
        </a-button>
        <a-button
          v-permission="'blog:links:reject'"
          type="primary"
          :disabled="selectedRowKeys.length !== 1"
          @click="handleReject"
        >
          <template #icon>
            <icon-edit />
          </template>
          {{ $t('searchTable.operation.reject') }}
        </a-button>
      </a-space>
    </a-col>
    <a-col
      :span="12"
      style="display: flex; align-items: center; justify-content: end"
    >
      <a-space :size="12">
        <a-button>
          <template #icon>
            <icon-download />
          </template>
          {{ $t('searchTable.operation.download') }}
        </a-button>
        <a-tooltip
          :content="$t('searchTable.actions.refresh')"
          @click="handleReFresh"
        >
          <div class="action-icon">
            <icon-refresh size="18" />
          </div>
        </a-tooltip>
        <a-dropdown @select="handleSelectDensity">
          <a-tooltip :content="$t('searchTable.actions.density')">
            <div class="action-icon">
              <icon-line-height size="18" />
            </div>
          </a-tooltip>
          <template #content>
            <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === size }"
            >
              <span>{{ item.name }}</span>
            </a-doption>
          </template>
        </a-dropdown>
      </a-space>
    </a-col>
  </a-row>
  <a-row style="flex: 1">
    <a-col :span="24">
      <a-table
        v-model:selected-keys="selectedRowKeys"
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="LinksList"
        :scroll="{ x: 2000, y: 'calc(100vh - 311px)' }"
        :bordered="false"
        :size="size"
        :pagination="pagination"
        column-resizable
        page-position="br"
        :row-selection="rowSelection"
        @page-change="handlePageNoChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #logo="{ record }">
          <a-image width="40px" height="40px" :src="record.logo" />
        </template>
        <template #status="{ record }">
          <a-tag :color="STATUS_CONFIG[record.status as StatusType].color">
            <template #icon>
              <component
                :is="STATUS_CONFIG[record.status as StatusType].icon"
              />
            </template>
            {{ STATUS_CONFIG[record.status as StatusType].text }}
          </a-tag>
        </template>
        <template #category="{ record }">
          <a-tag :color="CATEGORY_MAP[record.category as CategoryType].color">
            {{ CATEGORY_MAP[record.category as CategoryType].text }}
          </a-tag>
        </template>
        <template #operation="{ record }">
          <a-button
            v-permission="'blog:links:edit'"
            type="text"
            @click="handleEdit(record.id)"
          >
            {{ $t('searchTable.operation.edit') }}
          </a-button>
          <a-popconfirm
            :content="$t('modal.operation.tips')"
            @ok="handleDelete(record.id)"
          >
            <a-button v-permission="'blog:links:remove'" type="text">
              {{ $t('searchTable.operation.remove') }}
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-col>
  </a-row>
  <add-modal ref="addModalRef" @save-success="handleSaveSuccess" />
</template>

<style scoped lang="less">
  .action-icon {
    cursor: pointer;
  }
</style>
